/**
46 * <pre>
 * Copyright Notice:
 *    Copyright (c) 2005-2009 China Financial Certification Authority(CFCA)
 *    A-1 You An Men Nei Xin An Nan Li, Xuanwu District, Beijing ,100054, China
 *    All rights reserved.
 * 
 *    This software is the confidential and proprietary information of
 *    China Financial Certification Authority (&quot;Confidential Information&quot;).
 *    You shall not disclose such Confidential Information and shall use
 *    it only in accordance with the terms of the license agreement you
 *    entered into with CFCA.
 * </pre>
 */

package payment.simulator.institution.tx.common;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import payment.api.system.AggregateEnvironment;
import payment.api.system.TxMessenger;
import payment.api.tx.TxBaseResponse;
import payment.api.tx.aggregate.Tx5002Response;
import payment.api.tx.aggregate.Tx5003Response;
import payment.api.tx.aggregate.Tx5004Response;

/**
 * 发送同步交易请求到支付平台
 * 
 * <pre>
 * Modify Information:
 * Author       Date        Description
 * ============ =========== ============================
 * caohc        2018-12-03  新增
 * 
 * 
 * </pre>
 */
public class SendMessage4Aggregate extends HttpServlet {

    private static final long serialVersionUID = -9113676340998312853L;

    private static final Logger logger = Logger.getLogger("system");

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            // 获得参数message和signature
            String message = request.getParameter("message");
            String signature = request.getParameter("signature");
            String txCode = request.getParameter("txCode");
            String txName = request.getParameter("txName");
            // 与支付平台进行通讯
            TxMessenger txMessenger = new TxMessenger();
            String[] respMsg = null;
            
            // HTTP默认连接超时时间是25s，读超时时间是25s
            // HTTPS默认连接超时时间是50s，读超时时间是50s
            respMsg = txMessenger.send(message, signature, AggregateEnvironment.aggregateTxURL);// 0:message;
            // 设置连接超时时间和读超时时间
            // int connectTimeoutLimit = 50000; 设置连接超时时间（单位ms）
            // int readTimeoutLimit = 50000; 设置读超时时间（单位ms）
            // respMsg = txMessenger.send(message, signature,
            // connectTimeoutLimit, readTimeoutLimit,
            // AggregateEnvironment.aggregateTxURL);
            // 0:message;
            // 1:signature
            String plainText = new String(cpcn.institution.tools.util.Base64.decode(respMsg[0]), "UTF-8");

            logger.debug("[message]=[" + respMsg[0] + "]");
            logger.debug("[signature]=[" + respMsg[1] + "]");
            logger.debug("[plainText]=[" + plainText + "]");

            // 将结果保存在request中，以备在Response.jsp页面显示
            // //商户交易
            if ("5002".equals(txCode)) {
                Tx5002Response tx5002Response = new Tx5002Response(respMsg[0], respMsg[1]);
                request.setAttribute("txCode", txCode);
                request.setAttribute("txName", txName);
                request.setAttribute("plainText", tx5002Response.getResponsePlainText());
                if ("2000".equals(tx5002Response.getCode())) {
                    logger.info("[Message]=[" + tx5002Response.getMessage() + "]");
                    // 处理业务
                }
            } else if ("5003".equals(txCode)) {
                Tx5003Response tx5003Response = new Tx5003Response(respMsg[0], respMsg[1]);
                request.setAttribute("txCode", txCode);
                request.setAttribute("txName", txName);
                request.setAttribute("plainText", tx5003Response.getResponsePlainText());
                if ("2000".equals(tx5003Response.getCode())) {
                    logger.info("[Message]=[" + tx5003Response.getMessage() + "]");
                    // 处理业务
                }
            } else if ("5004".equals(txCode)) {
                Tx5004Response tx5004Response = new Tx5004Response(respMsg[0], respMsg[1]);
                request.setAttribute("txCode", txCode);
                request.setAttribute("txName", txName);
                request.setAttribute("plainText", tx5004Response.getResponsePlainText());
                if ("2000".equals(tx5004Response.getCode())) {
                    logger.info("[Message]=[" + tx5004Response.getMessage() + "]");
                    // 处理业务
                }
            } 
            
            // 转向Response.jsp页面
            request.getRequestDispatcher("/Response.jsp").forward(request, response);            
        } catch (Exception e) {
        	e.printStackTrace();
        	processException(request, response, e.getMessage());
        }
    }

    public void setRequestAttribute(HttpServletRequest request, TxBaseResponse txResponse, String txCode, String txName) {
        request.setAttribute("txCode", txCode);
        request.setAttribute("txName", txName);
        request.setAttribute("plainText", txResponse.getResponsePlainText());
        if ("2000".equals(txResponse.getCode())) {
            logger.info("[Message]=[" + txResponse.getMessage() + "]");
            // 处理业务
        }
    }

    private void processException(HttpServletRequest request, HttpServletResponse response, String errorMessage) {
        try {
            request.setAttribute("errorMessage", errorMessage);
            request.getRequestDispatcher("/ErrorPage.jsp").forward(request, response);
        } catch (Exception e) {
        }
    }

}